package com.saycode.common.aspect;

import com.saycode.common.Constant;
import com.saycode.common.beans.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Created by zhangyanhui on 2017/6/20.
 */
@Aspect
@Order(5)
@Component
public class SessionAspect {
    private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(public * com.saycode.back..controller.*Controller.*(..))")
    public void webLog(){}

    @Around("webLog()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        User user = (User) request.getSession().getAttribute(Constant.USER_SESSION_KEY);
        if(user == null){
            HttpServletResponse response = attributes.getResponse();
            request.getRequestDispatcher("/system/goLogin").forward(request,response);
        }else {
            pjp.proceed();
        }
    }
}
